package weibo4andriod.andriodexamples;


import weibo4andriod.Status;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import weibo4andriod.http.AccessToken;
import weibo4andriod.http.ImageItem;
import weibo4andriod.http.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;

public class OAuthActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timeline);
		
		Intent intent = getIntent();
		//if ("" == OAuthConstant.getInstance().getToken()){
			//Uri uri=this.getIntent().getData();
			String verifier = intent.getStringExtra("verifier");
			try {
				RequestToken requestToken= OAuthConstant.getInstance().getRequestToken();
				AccessToken accessToken=requestToken.getAccessToken(verifier);
				OAuthConstant.getInstance().setAccessToken(accessToken);
				saveToken(accessToken.getToken(), accessToken.getTokenSecret());
			} catch (WeiboException e) {
				e.printStackTrace();
			}
		//}
		
		Weibo weibo=OAuthConstant.getInstance().getWeibo();
		weibo.setToken(OAuthConstant.getInstance().getToken(), OAuthConstant.getInstance().getTokenSecret());
		
		try{
			Bundle bundle = intent.getExtras();
	    	ImageItem pic=new ImageItem("pic",bundle.getByteArray("imgData"));
	    	String url1=java.net.URLEncoder.encode("穿梭，时光。回到，最初。然后，穿越。在穿越，穿越，回到500年前，大闹天宫。 ","UTF-8");
	    	System.out.println(""+url1);
	    	Status status=weibo.uploadStatus(url1, pic);
	    	System.out.println("Successfully upload the status to ["
	    			+status.getText()+"].");
	    }
	    catch(Exception e1){
	        e1.printStackTrace();
	    }
	}
	
	private void saveToken(String token, String secret){
        //获得SharedPreferences对象
        SharedPreferences MyPreferences = getSharedPreferences("oauth", Activity.MODE_PRIVATE);
        //获得SharedPreferences.Editor
        SharedPreferences.Editor editor = MyPreferences.edit();
        //保存组件中的值

        editor.putString("token", token);
        editor.putString("secret", secret);
        //提交保存的结果
        editor.commit();
	}
}
